package com.cn.sl.server.api.system.log.aspect

import com.cn.sl.server.api.system.log.aspect.annotation.WriteLog
import com.cn.sl.server.api.system.log.aspect.service.ProcessLogService
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.AfterReturning
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.reflect.MethodSignature
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Component
import java.lang.reflect.Method

/**
 * @author 阮雪峰
 */
@Aspect
@Component
class LogAspect(val applicationContext: ApplicationContext) {

    var log: Logger = LoggerFactory.getLogger(LogAspect::class.java)

    @AfterReturning("@annotation(com.cn.sl.server.api.system.log.aspect.annotation.WriteLog)")
    fun doAfter(joinPoint: JoinPoint) {
        val target: Class<*> = joinPoint.target.javaClass
        val signature = joinPoint.signature as MethodSignature
        val method: Method
        try {
            method = target.getMethod(signature.name, *signature.parameterTypes)
            val targetAnnotation = target.getAnnotation(WriteLog::class.java)
            val methodAnnotation = method.getAnnotation(WriteLog::class.java)
            val processLogService: ProcessLogService =
                applicationContext.getBean(methodAnnotation.processClass.javaObjectType)
            processLogService.process(target, targetAnnotation, method, methodAnnotation, joinPoint)
        } catch (e: NoSuchMethodException) {
            log.error("方法未找到，类：{}， 方法：{}", target.name, signature.name)
        }
    }
}
